package com.weetop.aklyscan.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.google.zxing.activity.CaptureActivity;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnInputConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseFragment;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.TransferBoxBean;
import com.weetop.aklyscan.presenter.ZhongZXSearchPresent;
import com.weetop.aklyscan.utils.KeyBoardUtils;
import com.weetop.aklyscan.view.ZhongZXSearchView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;
import static com.weetop.aklyscan.utils.Constant.INTENT_EXTRA_KEY_QR_SCAN;

public class ZhuangXiangFragment extends BaseFragment<ZhongZXSearchPresent> implements ZhongZXSearchView {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.ll_headtitle)
    LinearLayout llHeadtitle;
    @BindView(R.id.rcy_data)
    RecyclerView rcyData;
    Unbinder unbinder;
    @BindView(R.id.tv_box_code)
    TextView tvBoxCode;
    @BindView(R.id.tv_product_count)
    TextView tvProductCount;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.tv_box_postion)
    TextView tvBoxPostion;
    @BindView(R.id.btn_scan)
    QMUIButton btnScan;
    private CommonRecyclerAdapter<TransferBoxBean.ItemsBean> adapter;
    private List<TransferBoxBean.ItemsBean> list = new ArrayList<>();

    @Override
    protected ZhongZXSearchPresent createPresenter() {
        return new ZhongZXSearchPresent(this, getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_zhuanxiang, null);
        unbinder = ButterKnife.bind(this, view);
        rcyData.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<TransferBoxBean.ItemsBean>(mActivity, R.layout.item_zhuanxiang, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, TransferBoxBean.ItemsBean item, int position) {
                helper.setText(R.id.tv_id, position + 1 + "");
                helper.setText(R.id.tv_code, item.getProduct_code());
                String itemName = TextUtils.isEmpty(item.getProduct_name()) ? "--" : item.getProduct_name();
                helper.setText(R.id.tv_name, itemName);
                //产品类型：1产品；2配件
                String productType = "--";
                if (item.getProduct_type() == 1) {
                    productType = "产品";
                } else if (item.getProduct_type() == 2) {
                    productType = "配件";
                }
                helper.setText(R.id.tv_type, productType);
                helper.setText(R.id.tv_count, item.getNumber() + "");
            }
        };
        rcyData.setAdapter(adapter);
        return view;
    }

    @Override
    public void getSearchResultSuccess(BaseModel<TransferBoxBean> o) {
        TransferBoxBean data = o.getData();
        tvBoxCode.setText(data.getBarcode());
        tvProductCount.setText(data.getAll_count() + "");
        tvStock.setText(data.getTier_name());
        tvBoxPostion.setText(data.getTier_code());
        List<TransferBoxBean.ItemsBean> items = data.getItems();
        list.clear();
        if (items != null && items.size() > 0) {
            list.addAll(items);
        }
        adapter.replaceAll(list);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    @OnClick(R.id.btn_scan)
    public void onViewClicked() {
        XPopup.get(getActivity()).asCenterList("请选择输入方式", new String[]{"扫一扫", "手动输入"},
                // null, /** 图标Id数组，可无 **/
                // 1,    /** 选中的position，默认没有选中效果 **/
                new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        if (position == 0) {
//                            ToastUtils.showShort("扫一扫");
                            startScanQrCode();
                        } else if (position == 1) {
                            XPopup.get(getContext()).asInputConfirm("中转箱条码", "请输入中转箱条码",
                                    new OnInputConfirmListener() {
                                        @Override
                                        public void onConfirm(String text) {
                                            KeyBoardUtils.closeKeybord(getView());
                                            String code = text.trim();
                                            if (!TextUtils.isEmpty(code)) {
                                                mPresenter.searchList(code);
                                            }
                                        }
                                    })
                                    .show();
                        }
                    }
                })
                .show();
    }


    private void startScanQrCode() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            requestPermissions(new String[]{Manifest.permission.CAMERA}, HUOJIA_CODE);
            return;
        }
        // 二维码扫描
        Intent intent = new Intent(getContext(), CaptureActivity.class);
        startActivityForResult(intent, REQUEST_HUOJIA_CODE_SCAN_ONE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null) {
            return;
        }
        switch (requestCode) {
            case HUOJIA_CODE:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startScanQrCode();
                } else {        // 授权被禁止
                    ToastUtils.showShort("请至权限中心打开本应用的相机访问权限");
                }
                break;
            default:
        }
    }

    /**
     * 扫码结果回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描结果回调
        if (requestCode == REQUEST_HUOJIA_CODE_SCAN_ONE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(INTENT_EXTRA_KEY_QR_SCAN);
            // scanResult 就是扫描二维码得到的字符串，再次可以根据自己的逻辑编写代码
            ToastUtils.showShort("扫码结果：" + scanResult);
            mPresenter.searchList(scanResult);
        }
    }
}